为了账号安全,请及时绑定邮箱和手机立即绑定

jQuery tips and tricks - 1

标签:
JQuery

There are many
articles about jQuery tips and tricks on the internet.

I am very happy to have so many resources for reference, and i will make my own
examples in order to learn these tips and tricks for a better work effective.

1. Get the DOM elements from a jQuery object

    $("div")[0];
    $("div").get(0);
    $("div").get()[0];

Note:get() returns all matched DOM elements in an array.

Get the tag name of a DOM node:

    $("body")[0].tagName.toLowerCase() === "body"; // true
    $("div").click(function() {
        this.tagName.toLowerCase() === "div"; //true
    });

2. Whether a jQuery object has DOM elements

    if($("div").length) {
        // there is at least one div DOM element in the page
    }
    // The following code snipppets do the same thing:
    // if($("div").size()) ...
    // if($("div")[0]) ...
    // if($("div").get(0)) ...

Beware of the this error decision:

    // if($("div")) ....

beacuse:

    !!$("div") // true
    !!$("no_thus_tag") // true
    !!$({}) // true

3. Find the index of an element

    <ul class="menu">
        <li>menu 1</li>
        <li>menu 2</li>
        <li>menu 3</li>
    </ul>
    $("ul.menu li").click(function() {
        // Find the index of this li node
        $(this).parent().find("li").index(this); // "menu 1" -> 0
    });

Or it can be write in a more effective way:

    var lis = $("ul.menu li");
    lis.click(function() {
        lis.index(this); // "menu 3" -> 2
    });

4. Bind event to ANY jQuery object, NOT only jQuery DOM object

In Athena client-side JavaScript framework, we need a global event publish&subscribe
mechanism:

    (function() {

        function eventNode() {
            var node = $("#_wbx_event");
            if (node.length === 0) {
                node = $("<div />").attr("id", "_wbx_event").appendTo("body");
            }
            return node;
        }

        $.wbx = $.wbx || {};
        $.wbx.util = {
            trigger: function() {
                var node = eventNode();
                node.trigger.apply(node, arguments);
            },

            bind: function() {
                var node = eventNode();
                node.bind.apply(node, arguments);
            }
        };

    })();

This code can also be wrote like this:

    (function() {

        var eventObj = $({});

        $.wbx = $.wbx || {};
        $.wbx.util = {
            trigger: function() {
                eventObj.trigger.apply(eventObj, arguments);
            },

            bind: function() {
                eventObj.bind.apply(eventObj, arguments);
            }
        };

    })();

Test code:

    $(function() {

        $.wbx.util.bind("custom_event_1", function(e, data) {
            // trigger custom_event_1 target_body
            alert("trigger custom_event_1 " + data);
        });

        $("body").click(function() {
            $.wbx.util.trigger("custom_event_1", ["target_body"]);
        });

    });

5. $.fn is just a shortcut of $.prototype

In fact, $ is a function and $.prototype is used to define functions that extend
the jQuery objects.

In the beginning, i was confused with the principle of jQuery:

If $ is a function, and we define a plugin like this $.prototype.plugin1 = function()
{};

It’s likely we should invoke our plugin this way:

    (new $("div")).plugin1();

But actually invocation:

    $("div").plugin1();

After review the jQuery source code, i understood the way jQuery works.

And this is a step by step tutorial to demostrate how can jQuery achieve this:

STEP 1:

    function W() {
    }
    W.prototype.plugin1 = function() {
        alert("plugin1");
    };
    (new W()).plugin1();

STEP 2:

    function W() {
        return new Q();
    }
    function Q() {
    }
    Q.prototype.plugin1 = function() {
        alert("plugin1");
    };
    W().plugin1();

STEP 3:

    function W() {
        return new Q();
    }
    function Q() {
    }
    Q.prototype = W.prototype;

    W.prototype.plugin1 = function() {
        alert("plugin1");
    };
    W().plugin1();

STEP 4:

    function W() {
        return new W.prototype.init();
    }
    W.prototype = {
        init: function() {
        }
    };
    W.prototype.init.prototype = W.prototype;

    W.prototype.plugin1 = function() {
        alert("plugin1");
    };
    W().plugin1();

STEP 5: The following is the way jQuery implement:

    jQuery = function(selector, context) {
        // The jQuery object is actually just the init constructor 'enhanced'
        return new jQuery.fn.init(selector, context);
    };

    jQuery.fn = jQuery.prototype = {
        init: function(selector, context) {
            var result = [];    // omit the implemention details
            return this.setArray(result);
        },
        setArray: function(elems) {
            // Resetting the length to 0, then using the native Array push
            // is a super-fast way to populate an object with array-like properties
            this.length = 0;
            Array.prototype.push.apply(this, elems);
            return this;
        }
    };
    // Give the init function the jQuery prototype for later instantiation
    jQuery.fn.init.prototype = jQuery.fn;
点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消